package swc.smu.ui.custom;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;

/**
 * Created by smu on 2016/5/5.
 * 1.侧边栏绘制上下左右；
 * 2.网格布局绘制；
 */
public class DefineGridView extends View implements ScaleGestureDetector.OnScaleGestureListener, View.OnTouchListener {
    static final int NONE = 0; //不做任何操作
    static final int DRAG = 1; //拖拽
    static final int ZOOM = 2; //缩放
    int optionMode = NONE;

    Paint paint = new Paint();
    Matrix initMatrix = new Matrix(); //界面初始化时的矩阵
    Matrix changeMatrix = new Matrix(); //变化之后的Matrix
    float fX, fY; //初始化触摸点坐标
    private float[] matrixValues = new float[9]; //变化后Matrix值存储

    float previousX, previousY; //手势移动的历史

    int left = 0, top = 0, right = 0, bottom = 0;//view距离各边界距离

    ScaleGestureDetector mScaleGestureDetector; //缩放手势监听

    public DefineGridView(Context context) {
        super(context);
        initDefineGridView(context, null);
    }

    public DefineGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initDefineGridView(context, attrs);
    }

    public DefineGridView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initDefineGridView(context, attrs);
    }

    public DefineGridView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes, Paint paint, float fX, float fY) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initDefineGridView(context, attrs);
    }

    private void initDefineGridView(Context context, AttributeSet attrs) {
        setOnTouchListener(this);
        paint.setColor(Color.RED);
        paint.setTextAlign(Paint.Align.CENTER);
        mScaleGestureDetector = new ScaleGestureDetector(context, this);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        Log.i("jss", "onAttachedToWindow()");
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        Log.i("jss", "onMeasure()");
        //存储当前view的宽高
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        Log.i("jss", "onLayout()"+left+"--"+top+"--"+right+"--"+bottom);
        this.left = left;
        this.top = top;
        this.right = right;
        this.bottom = bottom;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Log.i("jss", "onDraw()");
        initMatrix = canvas.getMatrix();
        float textSize = sp2px(14);
        String text = "自定义界面";
        paint.setTextSize(textSize);
        canvas.setMatrix(changeMatrix);
//        canvas.drawColor(Color.YELLOW);
//        canvas.drawText(text, 576, 960, paint);
        canvas.drawText(text, (left + canvas.getWidth() / 2), (top + canvas.getHeight() / 2) - textSize, paint);
        canvas.save();//保存当前的Matrix和 clip(裁剪)
    }

    /**
     * sp 转PX
     * @param f
     * @return
     */
    public float sp2px(float f) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, f, Resources.getSystem().getDisplayMetrics());
    }

    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        return false;
    }

    @Override
    public boolean onScaleBegin(ScaleGestureDetector detector) {
        Log.i("jss", "onScaleBegin");
        detector.getCurrentSpan();
        detector.getCurrentSpanX();
        return false;
    }

    @Override
    public void onScaleEnd(ScaleGestureDetector detector) {
        Log.i("jss", "onScaleEnd");
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        mScaleGestureDetector.onTouchEvent(event);
        // 1.获取当前触摸点的个数决定手势的操作类型：拖拽，缩放
        Log.i("jss", "event------------>"+event.getAction());
        gestureOption(event);
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: //第一个触摸点按下
                optionMode = DRAG;
                fX = event.getX();
                fY = event.getY();
                previousX = fX;
                previousY = fY;
                break;
            case MotionEvent.ACTION_POINTER_DOWN: //当屏幕上已经有一个点被按住，此时再按下其他点时触发。
                optionMode = ZOOM;
                // 若存在多个触摸点，则计算触摸点的中心点
                break;
            case MotionEvent.ACTION_MOVE: //手指移动
                Log.i("jss", "optionMode---->"+optionMode);
                if(optionMode == DRAG) { //拖拽
                    gestureDrag(event);
                } else if(optionMode == ZOOM) { //缩放
                    gestureZoom(event);
                    //这里缩放通过缩放手势监听来实现
                }
                break;
            case MotionEvent.ACTION_UP: //当屏幕上唯一的点被放开时触发
                optionMode = NONE; //不做任何操作
                break;
            case MotionEvent.ACTION_POINTER_UP: //当屏幕上有多个点被按住，松开其中一个点时触发（即非最后一个点被放开时）
                optionMode = DRAG; //拖拽
                break;
        }
        return true;
    }

    /**
     * 手势缩放
     * @param event
     */
    private void gestureZoom(MotionEvent event) {
        Log.i("jss", "gestureZoom");
        float x = event.getX();
        float y = event.getY();
        float zoomX = x-previousX;
        float zoomY = y-previousY;
        changeMatrix.setScale(zoomX, zoomY, previousX, previousY);
        invalidate();
    }

    /**
     * 拖拽手势
     */
    private void gestureDrag(MotionEvent event) {
        //1. 拖拽的方向；
        float x = event.getX();
        float y = event.getY();
        float xTran = x - previousX;
        float yTran = y - previousY;
        if(Math.abs(xTran) > 50 || Math.abs(yTran) > 50) {
            changeMatrix.setTranslate(xTran, yTran);
            invalidate();
//            previousX = x;
//            previousY = y;
        }

        int viewWidth = this.getWidth();
        int viewHeight = this.getHeight();
        //2. 判断是否允许拖拽，若布局拖拽方向小于该方向的尺寸，则不触发事件
    }

    /**
     * 获取view的缩放比例
     * @return
     */
    private float getZoomLevel() {
        changeMatrix.getValues(matrixValues);
        return matrixValues[Matrix.MSCALE_X];
    }

    /**
     * 计算多触摸点的中心点，若为单触摸点则为起始点
     * @param event
     */
    private void calcCenterPoint(MotionEvent event) {
        int count = event.getPointerCount();
        float x = 0, y = 0;
        for(int i = 0; i < count; i++) {
            x += event.getX(i);
            y += event.getY(i);
        }
        fX = x / count;
        fY = y / count;
    }

    /**
     * 根据触摸点的个数来确定手势操作的方法
     * @param event
     */
    private void gestureOption(MotionEvent event) {
        int size = event.getPointerCount();
        if(size == 1) {
            optionMode = DRAG;
        } else if(size > 1) {
            optionMode = ZOOM;
            calcCenterPoint(event);
        } else {
            optionMode = NONE;
        }
    }

}
